import { ref, computed } from 'vue';
import type { Ref } from 'vue';
import { getSeckillSkuInfo, getOrderGroupList } from '@/common/request/api';
import type { SeckillSkuInfo, GoodsSkuDetail, GoodsSkuSpecificationItem } from '@/common/request/api';
import { useQueryPage } from '@/common/hooks';
import { padZero } from '@/common/utils';

type Option = {
	goodsId: Ref<string>;
	skuInfo: Ref<GoodsSkuDetail>;
	checkInfo: Ref<GoodsSkuSpecificationItem | {}>;
	popupType: Ref<1 | 2>;
	updateGoodsPrice: (price: number) => void;
};
export const useActivity = ({ goodsId, skuInfo, checkInfo, popupType, updateGoodsPrice }: Option) => {
	let timer: number | undefined = undefined;
	const activityGoodsSkuId = ref(''); //参与活动的商品规格id
	const activityData = ref<SeckillSkuInfo>({
		flashSaleOldPrice: 0, //秒杀原来的价格
		flashSalePrice: 0, //秒杀价格
		flashSaleStock: 0, //秒杀剩余库存
		groupStock: 0, //拼团库存
		groupPrice: 0, //拼团价
		groupOldPrice: 0, //拼团原来的价格
		groupListTotal: 0,
		groupList: [],
		flashSale: {
			endTime: 0
		}
	});
	const hasWholesalePricing = ref<0 | 1>(0);
	const seckillTime = ref({
		day: '',
		hours: '',
		minute: '',
		seconds: ''
	});

	// 秒杀倒计时
	const countDown = () => {
		timer = setTimeout(() => {
			const endTime = new Date(activityData.value.flashSale.endTime).getTime();
			const nowTime = new Date().getTime();
			let __surplus = endTime - nowTime;
			if (__surplus < 0) {
				__surplus = 0;
			}
			const result = parseInt(`${__surplus / 1000}`);
			let day = padZero(Math.floor(result / (60 * 60 * 24)));
			let hours = padZero(Math.floor((result / 3600) % 24));
			let minute = padZero(Math.floor((result / 60) % 60));
			let seconds = padZero(Math.floor(result % 60));
			seckillTime.value = {
				day,
				hours,
				minute,
				seconds
			};
			countDown();
		}, 1000);
	};

	const speList = ref<SeckillSkuInfo['groupList']>([]); // 拼团列表
	const groupListTotal = ref(0);

	const clearActivityTimeout = () => {
		clearTimeout(timer);
		timer = undefined;
	};

	const requestParams = computed(() => {
		return {
			commodityId: goodsId.value
		};
	});

	const {
		list: allSpecList,
		handleQueryPage,
		handleRefresh
	} = useQueryPage({
		api: getOrderGroupList,
		option: {
			params: requestParams
		}
	});

	const showSpellPop = ref(false);
	const handleShowAllGroup = () => {
		showSpellPop.value = true;
		handleRefresh();
	};
	const getAllGroupList = () => {
		handleQueryPage();
	};
	// 拼团倒计时
	const startCountdown = (item: any) => {
		const overTime = new Date(item.overTime).getTime();
		const nowTime = new Date().getTime();
		if (overTime > nowTime) {
			const diff = overTime - nowTime;
			const result = parseInt(`${diff / 1000}`);
			let hours = padZero(Math.floor((result / 3600) % 24));
			let minute = padZero(Math.floor((result / 60) % 60));
			let seconds = padZero(Math.floor(result % 60));
			item.surplusTime = `${hours}:${minute}:${seconds}`;
			item.timer = setTimeout(() => {
				startCountdown(item);
			}, 1000);
		} else {
			// 清除当前已过期的拼团
			// this.speList.splice(this.speList.findIndex(list => list.id === item.id), 1)
			// this.allSpecList.splice(this.allSpecList.findIndex(list => list.id === item.id), 1)
			// if (this.groupListTotal) this.groupListTotal = this.groupListTotal - 1
			clearTimeout(item.timer);
			item.timer = null;
		}
	};
	const handleGetActivityData = () => {
		if (!activityGoodsSkuId.value) return;
		uni.showLoading({
			title: 'loading...'
		});
		getSeckillSkuInfo(activityGoodsSkuId.value)
			.then((res) => {
				if (res.data && res.data.type) {
					activityData.value = { ...res.data };
					hasWholesalePricing.value = 0;
					handleReplaceOriginalToActivityData();
					if (res.data.type === 1) {
						clearActivityTimeout();
						countDown();
					} else if (res.data.type === 2) {
						speList.value?.forEach((item) => {
							if (item.timer) {
								clearTimeout(item.timer);
								item.timer = undefined;
							}
						});
						speList.value = (JSON.parse(JSON.stringify(activityData.value?.groupList || [])) as SeckillSkuInfo['groupList'])?.map?.((item) => {
							item.overTime = item.overTime.replace(/-/g, '/');
							item.surplusTime = '00:00:00';
							startCountdown(item);
							return item;
						});

						groupListTotal.value = activityData.value.groupListTotal;
					}
				} else {
					activityGoodsSkuId.value = '';
				}
			})
			.finally(() => uni.hideLoading());
	};

	const handleReplaceOriginalToActivityData = () => {
		if (!skuInfo.value.productSkuSpecifications) return;
		skuInfo.value.productSkuSpecifications.some((item) => {
			if (item.id === activityGoodsSkuId.value) {
				checkInfo.value = item;
				if (activityData.value.type === 1) {
					(checkInfo.value as GoodsSkuSpecificationItem).price = activityData.value.flashSalePrice;
					(checkInfo.value as GoodsSkuSpecificationItem).stock = activityData.value.flashSaleStock;
					updateGoodsPrice(activityData.value.flashSalePrice);
				} else if (activityData.value.type === 2) {
					// 如果是直接购买，不用替换价格
					if (popupType.value === 1) {
						(checkInfo.value as GoodsSkuSpecificationItem).price = activityData.value.groupPrice;
						(checkInfo.value as GoodsSkuSpecificationItem).stock = activityData.value.groupStock;
						(checkInfo.value as GoodsSkuSpecificationItem).priceScribing = activityData.value.groupOldPrice;
						updateGoodsPrice(activityData.value.groupPrice);
					} else {
						(checkInfo.value as GoodsSkuSpecificationItem).price = activityData.value.groupOldPrice;
						updateGoodsPrice(activityData.value.groupOldPrice);
					}
				}
				return true;
			}
		});
		const __skukey = (checkInfo.value as GoodsSkuSpecificationItem).skuKey?.split?.('/');
		__skukey?.forEach((item, index) => {
			skuInfo.value.productSkus[index].productSkuValues.some((sku) => {
				if (sku.id == +item) {
					if (activityData.value.type === 1) {
						sku.price = activityData.value.flashSalePrice;
						sku.stock = activityData.value.flashSaleStock;
					} else if (activityData.value.type === 2) {
						// 同理
						if (popupType.value === 1) {
							sku.price = activityData.value.groupPrice;
							sku.stock = activityData.value.groupStock;
							sku.priceScribing = activityData.value.groupOldPrice;
						} else {
							sku.price = activityData.value.groupOldPrice;
						}
					}
					sku.isCheck = true;
				}
			});
		});
	};

	return {
		activityGoodsSkuId,
		activityData,
		allSpecList,
		groupListTotal,
		speList,
		showSpellPop,
		hasWholesalePricing,
		clearActivityTimeout,
		handleShowAllGroup,
		getAllGroupList,
		handleGetActivityData,
		handleReplaceOriginalToActivityData,
		seckillTime
	};
};
